using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Documents;
using System.Windows.Markup;
using System.Windows.Xps.Packaging;
using Common;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using Report;
using SExperiment;

namespace MainView.Windows
{
	public partial class ReportWindowForLizhu : Window, IComponentConnector
	{
		private Experiment _Experiment;

		protected string KeyDate = "$Date";

		protected string KeyReagentVer = "$ReagentVer";

		protected string KeyInsNum = "$InsNum";

		protected string KeyOperator = Utility.GetMessage("experimnet_result_operator");

		protected string KeyAssessor = Utility.GetMessage("experimnet_result_assessor");

		protected string KeyBCIQC = "$BCIQC";

		protected string KeyHIV2QC = "$HIV2QC";

		protected string KeyNegQC = "$NegQC";

		public ReportWindowForLizhu(Experiment experiment)
		{
			_Experiment = experiment;
			InitializeComponent();
			bntPrint.IsEnabled = false;
			BackgroundWorker backgroundWorker = new BackgroundWorker();
			backgroundWorker.DoWork += worker_DoWork;
			backgroundWorker.RunWorkerCompleted += worker_RunWorkerCompleted;
			backgroundWorker.RunWorkerAsync();
			tbError.Text = "Load...";
		}

		private void worker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
		{
			string text = e.Result as string;
			if (!File.Exists(text))
			{
				tbError.Text = "Create Report Error:" + text;
				return;
			}
			tbError.Text = string.Empty;
			XpsDocument xpsDocument = new XpsDocument(text, FileAccess.Read);
			IDocumentPaginatorSource fixedDocumentSequence = xpsDocument.GetFixedDocumentSequence();
			xpsDocument.Close();
			documentViewer.Document = fixedDocumentSequence;
			bntPrint.IsEnabled = true;
		}

		private void worker_DoWork(object sender, DoWorkEventArgs e)
		{
			try
			{
				string text = Utility.GetSystemTempFile() + ".xps";
				string sourceFileName = Utility.GetReportTemplatePath() + "Report_Lizhu.docx";
				string systemTempFile = Utility.GetSystemTempFile();
				string text2 = systemTempFile + ".docx";
				File.Copy(sourceFileName, text2, true);
				File.SetAttributes(text2, File.GetAttributes(text2) & ~FileAttributes.ReadOnly);
				string text3 = CreateReport(text2);
				if (string.IsNullOrEmpty(text3))
				{
					if (WordOperator.ExportToXPS(text2, text))
					{
						e.Result = text;
					}
					else
					{
						e.Result = "Create XPS File Error.";
					}
				}
				else
				{
					e.Result = text3;
				}
			}
			catch (Exception ex)
			{
				e.Result = ex.StackTrace;
			}
		}

		private void bntPrintSelect_Click(object sender, RoutedEventArgs e)
		{
			documentViewer.Print();
		}

		protected virtual void UpdatTableByKey(DocumentFormat.OpenXml.Wordprocessing.Table table, string key)
		{
			if (!(key == "孔位"))
			{
				return;
			}
			List<Well> list = _Experiment.Wells.Where((Well s) => s.Sample != null && s.Sample.PatientInfo.ID != "BCI positive" && s.Sample.PatientInfo.ID != "HIV2 positive" && s.Sample.PatientInfo.ID != "Negative").ToList();
			if (list.Count == 0 || list[0].Sample.Items.Count != 4)
			{
				return;
			}
			List<DocumentFormat.OpenXml.Wordprocessing.TableRow> list2 = new List<DocumentFormat.OpenXml.Wordprocessing.TableRow>();
			int num = -1;
			for (int i = 0; i < table.ChildElements.Count; i++)
			{
				DocumentFormat.OpenXml.Wordprocessing.TableRow tableRow = table.ChildElements[i] as DocumentFormat.OpenXml.Wordprocessing.TableRow;
				if (tableRow != null)
				{
					num++;
					if (num != 0)
					{
						list2.Add(tableRow);
					}
				}
			}
			if (list2.Count == 0)
			{
				return;
			}
			for (int num2 = list.Count - list2.Count; num2 > 0; num2--)
			{
				DocumentFormat.OpenXml.Wordprocessing.TableRow tableRow2 = list2[0].Clone() as DocumentFormat.OpenXml.Wordprocessing.TableRow;
				table.Append(tableRow2);
				list2.Add(tableRow2);
			}
			for (int j = 0; j < list.Count; j++)
			{
				DocumentFormat.OpenXml.Wordprocessing.TableRow tableRow3 = list2[j];
				int num3 = 0;
				for (int k = 0; k < tableRow3.ChildElements.Count; k++)
				{
					DocumentFormat.OpenXml.Wordprocessing.TableCell tableCell = tableRow3.ChildElements[k] as DocumentFormat.OpenXml.Wordprocessing.TableCell;
					if (tableCell == null)
					{
						continue;
					}
					num3++;
					string text = string.Empty;
					switch (num3)
					{
					case 1:
						text = list[j].Sample.WellNames;
						break;
					case 2:
						text = list[j].Sample.PatientInfo.ID;
						break;
					case 3:
						text = list[j].Sample.Items[0].Result.GetAllConclusion();
						break;
					case 4:
						text = list[j].Sample.Items[1].Result.GetAllConclusion();
						break;
					case 5:
						text = list[j].Sample.Items[3].Result.GetAllConclusion();
						break;
					case 6:
						text = list[j].Sample.Items[2].Result.GetAllConclusion();
						break;
					}
					List<Text> list3 = new List<Text>();
					List<Drawing> drawingList = new List<Drawing>();
					WordOperator.EnumerateTextAndDrawing(tableCell.ChildElements, list3, drawingList);
					if (list3.Count == 0)
					{
						bool flag = false;
						foreach (OpenXmlElement childElement in tableCell.ChildElements)
						{
							if (childElement is DocumentFormat.OpenXml.Wordprocessing.Paragraph)
							{
								childElement.Append(new DocumentFormat.OpenXml.Wordprocessing.Run(new Text(text)));
								flag = true;
								break;
							}
						}
						if (!flag)
						{
							tableCell.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new Text(text))));
						}
					}
					else
					{
						list3[0].Text = text;
						for (int l = 1; l < list3.Count; l++)
						{
							list3[l].Text = string.Empty;
						}
					}
				}
			}
		}

		private void UpdateTable(DocumentFormat.OpenXml.Wordprocessing.Table table)
		{
			bool flag = false;
			for (int i = 0; i < table.ChildElements.Count; i++)
			{
				if (flag)
				{
					break;
				}
				DocumentFormat.OpenXml.Wordprocessing.TableRow tableRow = table.ChildElements[i] as DocumentFormat.OpenXml.Wordprocessing.TableRow;
				if (tableRow == null)
				{
					continue;
				}
				for (int j = 0; j < tableRow.ChildElements.Count; j++)
				{
					if (flag)
					{
						break;
					}
					DocumentFormat.OpenXml.Wordprocessing.TableCell tableCell = tableRow.ChildElements[j] as DocumentFormat.OpenXml.Wordprocessing.TableCell;
					if (tableCell == null)
					{
						continue;
					}
					List<Text> list = new List<Text>();
					List<Drawing> drawingList = new List<Drawing>();
					WordOperator.EnumerateTextAndDrawing(tableCell.ChildElements, list, drawingList);
					StringBuilder stringBuilder = new StringBuilder();
					foreach (Text item in list)
					{
						stringBuilder.Append(item.Text);
					}
					if (stringBuilder.Length > 0)
					{
						UpdatTableByKey(table, stringBuilder.ToString());
					}
					flag = true;
					break;
				}
			}
		}

		public virtual string CreateReport(string report)
		{
			WordprocessingDocument wordprocessingDocument = null;
			try
			{
				wordprocessingDocument = WordprocessingDocument.Open(report, true);
				Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
				List<Text> textList = new List<Text>();
				List<Drawing> drawingList = new List<Drawing>();
				WordOperator.EnumerateTextAndDrawing(body.ChildElements, textList, drawingList);
				foreach (HeaderPart headerPart in wordprocessingDocument.MainDocumentPart.HeaderParts)
				{
					WordOperator.EnumerateTextAndDrawing(headerPart.Header.ChildElements, textList, drawingList);
				}
				foreach (FooterPart footerPart in wordprocessingDocument.MainDocumentPart.FooterParts)
				{
					WordOperator.EnumerateTextAndDrawing(footerPart.Footer.ChildElements, textList, drawingList);
				}
				UpdateBasicInfo(textList);
				List<DocumentFormat.OpenXml.Wordprocessing.Table> list = new List<DocumentFormat.OpenXml.Wordprocessing.Table>();
				WordOperator.EnumerateTable(body.ChildElements, list);
				foreach (DocumentFormat.OpenXml.Wordprocessing.Table item in list)
				{
					UpdateTable(item);
				}
				foreach (HeaderPart headerPart2 in wordprocessingDocument.MainDocumentPart.HeaderParts)
				{
					textList = new List<Text>();
					drawingList = new List<Drawing>();
					WordOperator.EnumerateTextAndDrawing(headerPart2.Header.ChildElements, textList, drawingList);
					UpdateBasicInfo(textList);
				}
				return string.Empty;
			}
			catch (Exception ex)
			{
				return ex.StackTrace;
			}
			finally
			{
				if (wordprocessingDocument != null)
				{
					wordprocessingDocument.Close();
					wordprocessingDocument = null;
				}
			}
		}

		private void UpdateBasicInfo(List<Text> textList)
		{
			if (textList == null || textList.Count == 0)
			{
				return;
			}
			StringBuilder stringBuilder = new StringBuilder();
			foreach (Text text3 in textList)
			{
				stringBuilder.Append(text3.Text);
			}
			string text = stringBuilder.ToString();
			int startIndex = 0;
			int num = 0;
			int num2 = 0;
			List<WordKey> list = new List<WordKey>();
			while ((startIndex = text.IndexOf("$", startIndex)) != -1)
			{
				num2 = text.IndexOf("#", startIndex);
				num = text.IndexOf("$", startIndex + 1);
				if (num != -1 && num < num2)
				{
					startIndex++;
					continue;
				}
				WordKey key = GetKey(text.Substring(startIndex, num2 - startIndex + 1));
				if (key != null)
				{
					list.Add(key);
					string text2 = "";
					int num3 = 0;
					for (int i = 0; i < textList.Count; i++)
					{
						if (text2 == key.Content)
						{
							break;
						}
						if (!string.IsNullOrEmpty(text2))
						{
							if (textList[i].Text.Length < key.Content.Length - text2.Length)
							{
								text2 += textList[i].Text;
								textList[i].Text = "";
							}
							else
							{
								textList[i].Text = textList[i].Text.Remove(0, key.Content.Length - text2.Length);
								text2 = key.Content;
							}
						}
						if (startIndex >= num3 && startIndex < num3 + textList[i].Text.Length)
						{
							int num4 = startIndex - num3;
							if (textList[i].Text.Length - num4 < key.Content.Length)
							{
								text2 = textList[i].Text.Substring(num4, textList[i].Text.Length - num4);
								textList[i].Text = textList[i].Text.Remove(num4, textList[i].Text.Length - num4) + key.Content;
							}
						}
						num3 += textList[i].Text.Length;
					}
				}
				startIndex++;
			}
			foreach (WordKey item in list)
			{
				string keyValue = GetKeyValue(item);
				if (item.IsSymbol)
				{
					foreach (Text text4 in textList)
					{
						if (text4.Text.Contains(item.Content))
						{
							DocumentFormat.OpenXml.Wordprocessing.Run run = text4.Parent as DocumentFormat.OpenXml.Wordprocessing.Run;
							if (run != null)
							{
								run.RemoveChild(text4);
								SymbolChar symbolChar = new SymbolChar();
								symbolChar.Font = "Wingdings";
								symbolChar.Char = keyValue;
								SymbolChar symbolChar2 = symbolChar;
								run.Append(symbolChar2);
							}
						}
					}
					continue;
				}
				foreach (Text text5 in textList)
				{
					text5.Text = text5.Text.Replace(item.Content, keyValue);
				}
			}
		}

		protected virtual WordKey GetKey(string text)
		{
			string text2 = null;
			if (text.IndexOf(KeyDate) == 0)
			{
				text2 = KeyDate;
			}
			else if (text.IndexOf(KeyReagentVer) == 0)
			{
				text2 = KeyReagentVer;
			}
			else if (text.IndexOf(KeyInsNum) == 0)
			{
				text2 = KeyInsNum;
			}
			else if (text.IndexOf(KeyOperator) == 0)
			{
				text2 = KeyOperator;
			}
			else if (text.IndexOf(KeyAssessor) == 0)
			{
				text2 = KeyAssessor;
			}
			else if (text.IndexOf(KeyBCIQC) == 0)
			{
				text2 = KeyBCIQC;
			}
			else if (text.IndexOf(KeyHIV2QC) == 0)
			{
				text2 = KeyHIV2QC;
			}
			else if (text.IndexOf(KeyNegQC) == 0)
			{
				text2 = KeyNegQC;
			}
			if (!string.IsNullOrEmpty(text2))
			{
				WordKey wordKey = new WordKey();
				wordKey.Key = text2;
				wordKey.Content = text;
				return wordKey;
			}
			return null;
		}

		protected virtual string GetKeyValue(WordKey wordKey)
		{
			if (wordKey.Key == KeyDate)
			{
				return _Experiment.Device.StartTime.ToString("yyyy-M-d");
			}
			if (wordKey.Key == KeyReagentVer)
			{
				return _Experiment.Note;
			}
			if (wordKey.Key == KeyInsNum)
			{
				return _Experiment.Device.Series;
			}
			if (wordKey.Key == KeyOperator)
			{
				return _Experiment.Operator;
			}
			if (wordKey.Key == KeyAssessor)
			{
				return _Experiment.Auditor;
			}
			if (wordKey.Key == KeyBCIQC)
			{
				Well well = _Experiment.Wells.Where((Well s) => s.Sample != null && s.Sample.PatientInfo.ID == "BCI positive").FirstOrDefault();
				if (well != null)
				{
					return well.Sample.Result.GetAllConclusion();
				}
			}
			else if (wordKey.Key == KeyHIV2QC)
			{
				Well well2 = _Experiment.Wells.Where((Well s) => s.Sample != null && s.Sample.PatientInfo.ID == "HIV2 positive").FirstOrDefault();
				if (well2 != null)
				{
					return well2.Sample.Result.GetAllConclusion();
				}
			}
			else if (wordKey.Key == KeyNegQC)
			{
				Well well3 = _Experiment.Wells.Where((Well s) => s.Sample != null && s.Sample.PatientInfo.ID == "Negative").FirstOrDefault();
				if (well3 != null)
				{
					return well3.Sample.Result.GetAllConclusion();
				}
			}
			return string.Empty;
		}
	}
}
